<template>
  <div class="app-container">


        <el-form :model="queryParams.domain" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="登录名" prop="loginName">
            <el-input
              v-model="queryParams.domain.loginName"
              placeholder="登录名"
              clearable
              size="small"
              style="width: 120px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model="queryParams.domain.realName"
              placeholder="真实姓名"
              clearable
              size="small"
              style="width: 120px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.domain.phonenumber"
              placeholder="手机号码"
              clearable
              size="small"
              style="width: 120px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>


        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column label="登录名" align="center" key="loginName" prop="loginName" :show-overflow-tooltip="true" />
          <el-table-column label="真实姓名" align="center" key="realName" prop="realName" :show-overflow-tooltip="true" />
          <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" :show-overflow-tooltip="true"/>
          <el-table-column label="角色" align="center" key="roleName" prop="roleName" :show-overflow-tooltip="true" />
          <el-table-column label="用户邮箱" align="center" key="email" prop="email" :show-overflow-tooltip="true" />
          <el-table-column label="公司名称" align="center" key="orgName" prop="orgName" :show-overflow-tooltip="true" />
          <el-table-column label="创建时间" align="center" key="createTime" prop="createTime" :show-overflow-tooltip="true" />
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:user:edit']"
              >修改</el-button>
              <el-button
                v-if="scope.row.userId !== 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:user:remove']"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-key"
                @click="handleResetPwd(scope.row)"
                v-hasPermi="['system:user:resetPwd']"
              >重置</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />


    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录名" prop="loginName">
              <el-input v-model="form.loginName" placeholder="请输入登录名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入真实姓名"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
         <el-form-item label="用户类型" prop="userType"   v-hasPermi="['lable:userType:show']" >
             <el-radio-group v-model="form.userType" @change="getUserTypeFromRadio">
               <el-radio :label="0" >个人用户</el-radio>
               <el-radio :label="1" >公司用户</el-radio>
             </el-radio-group>
           </el-form-item>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-show="userType == 1" v-hasPermi="['label:orgName:show']">
          <el-col :span="12">
            <el-form-item label="公司名称" prop="orgId">
              <el-select v-model="form.orgId" placeholder="请选择" filterable>
                <el-option
                  v-for="item in deptOptions"
                  :key="item.orgId"
                  :label="item.orgName"
                  :value="item.orgId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="角色名称" prop="roleId">
              <el-select v-model="form.roleId" placeholder="请选择" filterable>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱"/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="注释">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入注释" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, listCanDoRole,findUser,  listAlldept} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { downXlxsFormRes} from "@/utils/admin";
export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      //部门
      deptOptions: [],
      //部门名称
      deptName: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],

      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "orgName"
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData"
      },
      userType:1,
      // 查询参数
      queryParams: {
        domain:{
          loginName: "",
          phonenumber: "",
          realName: ""
        },
        pageNum: 1,
        pageSize: 10,
        sortName: "",
        sortOrder: "",
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: false },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 7, label: `创建时间`, visible: true },
        { key: 5, label: `用户邮箱`, visible: true }
      ],
      // 表单校验
      rules: {
        loginName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { max: 20, message: "用户名称长度最大为20", trigger: "blur" },
          { min: 4, message: "用户名称长度最小为4", trigger: "blur" },
          { pattern: /^[a-zA-Z0-9_-]{0,}$/, message: "用户名称只能包含字母、数字、-、_", trigger: "blur" }
        ],
        realName: [
          { required: true, message: "真实姓名不能为空", trigger: "blur" },
          { max: 5, message: "真实姓名长度最大为5", trigger: "blur" },
          { pattern: /^[\u4e00-\u9fa5]{0,}$/, message: "真实姓名只能为汉字", trigger: "blur" }
        ],
        orgId: [
          { required: this.userType == 1, message: "部门不能为空", trigger: "change" }
        ],
        roleId: [
          { required: true, message: "角色不能为空", trigger: "change" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    //状态
    this.statusOptions = [{"dictValue":"","dictLabel":"全部"},{"dictValue":"0","dictLabel":"启用"},{"dictValue":"1","dictLabel":"停用"}],
    //性别
    this.sexOptions =  [{"dictValue":"0","dictLabel":"男"},{"dictValue":"1","dictLabel":"女"},{"dictValue":"2","dictLabel":"未知"}];
    //查询角色
    listCanDoRole(this.queryParams).then((response) => {  this.roleOptions = response.data;});

    listAlldept().then(res =>{this.deptOptions = res.data;});
  },
  methods: {
    getUserTypeFromRadio(defaultValue){
      if(typeof(defaultValue) == undefined){
        let value = this.radio;
      }
      this.userType = defaultValue;
      console.log(this.userType)
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
          this.userList = response.data.records;
          this.total = response.data.total;
          this.loading = false;
        }).catch((err) => {
         this.loading = false;
        });
    },

    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.orgName.indexOf(value) !== -1;
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.domain.orgId = data.orgId;
      this.handleQuery();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        email: "",
        loginName: "",
        orgId: "",
        phonenumber: "",
        realName: "",
        remark: "",
        sex: "",
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.pageNum = 1;
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$modal.loading("加载中");
      findUser().then(res =>{
        this.form = res.data;
        this.open = true;
        this.title = "添加用户";
        this.$modal.closeLoading();
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.open = true;
      this.title = "修改用户";
      this.form = JSON.parse(JSON.stringify(row))
      this.userType = this.form.userType;

    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.loginName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then(({ value }) => {
          resetUserPwd(row.userId, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log('===row',row);
      const userIds = row.userId || this.ids;
      this.$confirm('是否确认删除用户"' + row.loginName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUser(userIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
    },


  }
};
</script>
<style scoped>
.sg-btnGrounp{
  text-align: right;
  margin: 15px;
}
</style>
